package com.cqie.hospitalescort.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cqie.hospitalescort.DTO.ChatInfoDTO;
import com.cqie.hospitalescort.entity.EscortInfo;
import com.cqie.hospitalescort.entity.OnlineChatInfo;
import com.cqie.hospitalescort.entity.UserInfo;
import com.cqie.hospitalescort.exception.BusinessException;
import com.cqie.hospitalescort.mapper.EscortInfoMapper;
import com.cqie.hospitalescort.mapper.OnlineChatInfoMapper;
import com.cqie.hospitalescort.mapper.UserInfoMapper;
import com.cqie.hospitalescort.service.OnlineChatInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author gdy
 * @since 2025-02-18
 */
@Service
public class OnlineChatInfoServiceImpl extends ServiceImpl<OnlineChatInfoMapper, OnlineChatInfo> implements OnlineChatInfoService {

    @Autowired
    private OnlineChatInfoMapper chatInfoMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private EscortInfoMapper escortInfoMapper;

    /**
     * 保存消息
     *
     * @param chatInfo
     */
    @Override
    @Transactional
    public void saveMessage(OnlineChatInfo chatInfo) {
        chatInfoMapper.insert(chatInfo);
    }

    /**
     * 消息记录
     *
     * @param chatCode
     * @return
     */
    @Override
    public List<ChatInfoDTO> getMessagesByChatCode(String chatCode) {
        QueryWrapper<OnlineChatInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("chat_code", chatCode);
        return chatInfoMapper.selectList(queryWrapper).stream()
                .filter(Objects::nonNull)
                .map(t -> {
                    ChatInfoDTO infoDTO = t.toChatInfoDTO();
                    infoDTO.setUsername(getNickNameById(t.getUserId()));
                    infoDTO.setEscortName(getNameById(t.getEscortId()));
                    return infoDTO;
                })
                .collect(Collectors.toList());
    }


    /**
     * 用户姓名
     *
     * @param id
     * @return
     */
    private String getNickNameById(Long id) {
        UserInfo userInfo = userInfoMapper.selectById(id);
        if (Objects.isNull(userInfo)) {
            throw new BusinessException("用户未找到！");
        }
        return userInfo.getNickname();
    }

    /**
     * 陪诊员姓名
     *
     * @param id
     * @return
     */
    private String getNameById(Long id) {
        EscortInfo escortInfo = escortInfoMapper.selectById(id);
        if (Objects.isNull(escortInfo)) {
            throw new BusinessException("用户未找到！");
        }
        return escortInfo.getName();
    }

}
